﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using FrbaBus.Core;


namespace FrbaBus.Compra_de_Pasajes
{
    public partial class RealizarPago : Form
    {
        public RealizarPago()
        {
            InitializeComponent();
        }
        private CompraPasajes parent = null;
        private int nuevatarjeta = 0;
        private int tarjeta = 0;
        public RealizarPago(Form callingForm)
        {
            parent = callingForm as CompraPasajes;

            InitializeComponent();
        }
        private void RealizarPago_Load(object sender, EventArgs e)
        {
            DBManager db = new DBManager();
            SqlCommand consulta11 = new SqlCommand("select distinct Tipo_Tarjeta from ALL_IN.Cuota_Disponible");
            SQLResponse r11 = db.executeQuery(consulta11);
            SqlCommand consulta12 = new SqlCommand("select count(distinct Tipo_Tarjeta) from ALL_IN.Cuota_Disponible");
            SQLResponse r12 = db.executeQuery(consulta12);
            int valor2 = (int)r12.result.Rows[0][0];
            for (int i = 0; i < valor2; i++)
            {
                comboBox1.Items.Add(r11.result.Rows[i][0]);
            }

            string usuariovalor = "";
            usuariovalor = Login.Login.usuariovalor;
            if (usuariovalor == "Cliente")
            {
                button1.Visible = false;
            }
            Compra_de_Pasajes.CompraPasajes frm = new Compra_de_Pasajes.CompraPasajes();
            label2.Text = Compra_de_Pasajes.CompraPasajes.pago.ToString();
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            groupBox2.Visible = true;
            button3.Visible = true;
            label3.Visible = true;
            textBox1.Visible = true;
            tarjeta = 1;
            textBox6.Text = "Tarjeta";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Compra_de_Pasajes.Cliente frm = new Compra_de_Pasajes.Cliente(this);
            frm.ShowDialog(this);
        }

        private void text_changed(object sender, EventArgs e)
        {
            if (tarjeta == 1)
            {
                if (textBox1.Text != "")
                {
                    DBManager db = new DBManager();
                    SqlCommand consulta = new SqlCommand("select ALL_IN.existetarjeta2 ('" + textBox1.Text + "')");
                    SQLResponse r = db.executeQuery(consulta);
                    if (r.result.Rows[0][0].ToString() == "False")
                    {
                        MessageBox.Show("Por favor cargue los datos de la tarjeta.");
                        nuevatarjeta = 1;
                        textBox2.Enabled = true;
                        textBox3.Enabled = true;
                        textBox4.Enabled = true;
                        textBox5.Enabled = true;
                        comboBox1.Enabled = true;
                        checkBox1.Enabled = true;
                    }
                    else
                    {
                        textBox2.Enabled = false;
                        textBox3.Enabled = false;
                        textBox4.Enabled = false;
                        textBox5.Enabled = false;
                        comboBox1.Enabled = false;
                        checkBox1.Enabled = true;
                        SqlCommand consulta2 = new SqlCommand("select * from ALL_IN.Tarjeta where cli_dni='" + textBox1.Text + "'");
                        SQLResponse r2 = db.executeQuery(consulta2);
                        textBox2.Text = r2.result.Rows[0][0].ToString();
                        textBox3.Text = r2.result.Rows[0][1].ToString();
                        textBox4.Text = r2.result.Rows[0][4].ToString();
                        textBox5.Text = r2.result.Rows[0][5].ToString();
                        comboBox1.Text = r2.result.Rows[0][2].ToString();

                    }
                    
                }
            }
        }
        private void textchanged(object sender, KeyPressEventArgs e)
        {
            int i = e.KeyChar;
            if (i >= 48 && i <= 57 || i == 8 || i == 13)
            {
            }
            else
            {
                MessageBox.Show("Solo están permitidos caracteres numéricos.");
                e.Handled = true;
            }
        }
        

        private void button4_Click(object sender, EventArgs e) 
        {
            if (tarjeta == 1)//Tarjeta
            {
                if (textBox1.Text == "" || textBox2.Text == "" || textBox4.Text == "" || textBox3.Text == "" || textBox5.Text == "" || comboBox1.Text == "")
                {
                    MessageBox.Show("Debe completar todos los campos.");
                }
                else
                {
                    DialogResult dialogResult = MessageBox.Show("¿Confirmar la realizacion de la compra?", "Confirmacion de Compra", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {

                        if (nuevatarjeta == 1)//Nueva Tarjeta
                        {
                            int couta = 0;
                            DBManager db = new DBManager();
                            SqlCommand consulta = new SqlCommand("select max(Nro_transaccion) from ALL_IN.Pagos");
                            SQLResponse r = db.executeQuery(consulta);
                            int trans = int.Parse(r.result.Rows[0][0].ToString()) + 1;
                            if (checkBox1.Checked == true)
                            {
                                couta = 1;
                            }
                            SqlCommand consulta3 = new SqlCommand("select ALL_IN.existeTarjeta ('" + textBox2.Text + "')");
                            SQLResponse r3 = db.executeQuery(consulta3);
                            if (r3.result.Rows[0][0].ToString() == "True")
                            {
                                MessageBox.Show("Ya existe ese numero de tarjeta. Por favor, coloque otro numero de tarjeta.");
                            }
                            else
                            {
                                SqlCommand consulta2 = new SqlCommand("insert into ALL_IN.Tarjeta values ('" + textBox2.Text + "','" + textBox3.Text + "','" + comboBox1.Text + "','" + textBox1.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')");
                                db.executeQuery(consulta2);
                                SqlCommand consulta4 = new SqlCommand("insert into ALL_IN.Pagos values ('" + trans.ToString() + "','" + textBox1.Text + "','" + textBox2.Text + "','" + couta.ToString() + "')");
                                db.executeQuery(consulta4);
                                int i = 0;
                                for (i = 0; (i <= parent.dataGridView1.Rows.Count - 1); i++)
                                {
                                    SqlCommand consulta6 = new SqlCommand("select max(Nro_Pasaje) from ALL_IN.Disponibilidad_Butaca");
                                    SQLResponse r6 = db.executeQuery(consulta6);
                                    int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                    string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                    string[] words2 = words[2].Split(' ');
                                    string dia1 = words2[0];
                                    string mes1 = words[1];
                                    string anio1 = words[0];
                                    string time1 = words2[1];
                                    string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                    DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                    string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                    string[] words3 = parent.dataGridView1.Rows[i].Cells[4].Value.ToString().Split(',');
                                    string monto = words3[0];
                                    string monto2 = "";
                                    int size = words3.Length;
                                    if (size == 1)
                                    {
                                        monto2 = "0";
                                    }
                                    else
                                    {
                                        monto2 = words3[1];
                                    }
                                    SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_Butaca values('" + trans6.ToString() + "','" + fecha_salida + "','" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "','" + int.Parse(parent.dataGridView1.Rows[i].Cells[1].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + int.Parse(textBox1.Text) + "','" + trans + "'," + monto + "." + monto2 + ",'0')");
                                    db.executeQuery(consulta5);

                                }
                                for (i = 0; (i <= parent.dataGridView3.Rows.Count - 1); i++)
                                {
                                    SqlCommand consulta6 = new SqlCommand("select max(Nro_Paquete) from ALL_IN.Disponibilidad_kg");
                                    SQLResponse r6 = db.executeQuery(consulta6);
                                    int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                    string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                    string[] words2 = words[2].Split(' ');
                                    string dia1 = words2[0];
                                    string mes1 = words[1];
                                    string anio1 = words[0];
                                    string time1 = words2[1];
                                    string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                    DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                    string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                    string[] words3 = parent.dataGridView3.Rows[i].Cells[1].Value.ToString().Split(',');
                                    string monto = words3[0];
                                    string monto2 = "";
                                    int size = words3.Length;
                                    if (size == 1)
                                    {
                                        monto2 = "0";
                                    }
                                    else
                                    {
                                        monto2 = words3[1];
                                    }
                                    SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_kg values('" + trans6.ToString() + "',convert(datetime,'" + fecha_salida + "',120),'" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + textBox1.Text + "','" + parent.dataGridView3.Rows[i].Cells[2].Value.ToString() + "','" + trans + "','" + monto + "." + monto2 + "','0')");
                                    db.executeQuery(consulta5);

                                }

                            }
                            MessageBox.Show("Se ha realizado la compra!." + "\n" + "TOTAL: $" + label2.Text + "\n" + "Nro. Voucher: " + trans); // TODO: Mostrar los datos finales.
                            parent.dataGridView1.Rows.Clear();
                            parent.dataGridView2.Rows.Clear();
                            parent.dataGridView3.Rows.Clear();
                            this.Close();
                        }
                        else //Tarjeta ya existente
                        {
                            int couta = 0;
                            DBManager db = new DBManager();
                            SqlCommand consulta = new SqlCommand("select max(Nro_transaccion) from ALL_IN.Pagos");
                            SQLResponse r = db.executeQuery(consulta);
                            int trans = int.Parse(r.result.Rows[0][0].ToString()) + 1;
                            if (checkBox1.Checked == true)
                            {
                                couta = 1;
                            }
                                SqlCommand consulta4 = new SqlCommand("insert into ALL_IN.Pagos values ('" + trans.ToString() + "','" + textBox1.Text + "','" + textBox2.Text + "','" + couta.ToString() + "')");
                                db.executeQuery(consulta4);
                                int i = 0;
                                for (i = 0; (i <= parent.dataGridView1.Rows.Count - 1); i++)
                                {
                                    SqlCommand consulta6 = new SqlCommand("select max(Nro_Pasaje) from ALL_IN.Disponibilidad_Butaca");
                                    SQLResponse r6 = db.executeQuery(consulta6);
                                    int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                    string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                    string[] words2 = words[2].Split(' ');
                                    string dia1 = words2[0];
                                    string mes1 = words[1];
                                    string anio1 = words[0];
                                    string time1 = words2[1];
                                    string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                    DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                    string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                    string[] words3 = parent.dataGridView1.Rows[i].Cells[4].Value.ToString().Split(',');
                                    string monto = words3 [0];
                                    string monto2 = "";
                                    int size = words3.Length;
                                    if (size == 1)
                                    {
                                        monto2 = "0";
                                    }
                                    else
                                    {
                                        monto2 = words3[1];
                                    }
                                    SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_Butaca values('" + trans6.ToString() + "',convert(datetime,'" + fecha_salida + "',120),'" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "','" + int.Parse(parent.dataGridView1.Rows[i].Cells[1].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + int.Parse(textBox1.Text) + "','" + trans + "'," + monto + "." + monto2 + ",'0')");
                                    db.executeQuery(consulta5);

                                }
                                for (i = 0; (i <= parent.dataGridView3.Rows.Count - 1); i++)
                                {
                                    SqlCommand consulta6 = new SqlCommand("select max(Nro_Paquete) from ALL_IN.Disponibilidad_kg");
                                    SQLResponse r6 = db.executeQuery(consulta6);
                                    int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                    string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                    string[] words2 = words[2].Split(' ');
                                    string dia1 = words2[0];
                                    string mes1 = words[1];
                                    string anio1 = words[0];
                                    string time1 = words2[1];
                                    string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                    DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                    string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                    string[] words3 = parent.dataGridView3.Rows[i].Cells[1].Value.ToString().Split(',');
                                    string monto = words3[0];
                                    string monto2 = "";
                                    int size = words3.Length;
                                    if (size == 1)
                                    {
                                        monto2 = "0";
                                    }
                                    else
                                    {
                                        monto2 = words3[1];
                                    }
                                   
                                    SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_kg values('" + trans6.ToString() + "',convert(datetime,'" + fecha_salida + "',120),'" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + textBox1.Text + "','" + parent.dataGridView3.Rows[i].Cells[2].Value.ToString() + "','" + trans + "','" + monto + "." + monto2 + "','0')");
                                    db.executeQuery(consulta5);
                                }
                                MessageBox.Show("Se ha realizado la compra!." + "\n" + "TOTAL: $" + label2.Text + "\n" + "Nro. Voucher: " + trans); // TODO: Mostrar los datos finales.
                                parent.dataGridView1.Rows.Clear();
                                parent.dataGridView2.Rows.Clear();
                                parent.dataGridView3.Rows.Clear();
                                this.Close();
                        }
                    }
                    else //No acepta la compra
                    {
                        
                        textBox2.Text = "";
                        textBox3.Text = "";
                        textBox4.Text = "";
                        textBox5.Text = "";
                        textBox5.ReadOnly = true;
                        textBox4.ReadOnly = true;
                        textBox3.ReadOnly = true;
                        textBox2.ReadOnly = true;

                        comboBox1.Text = "";

                    }
                }
            }
            else //Efectivo
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("Debe completar todos los campos.");
                }
                else
                {
                    DialogResult dialogResult = MessageBox.Show("¿Confirmar la realizacion de la compra?", "Confirmacion de Compra", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        int couta = 0;
                        DBManager db = new DBManager();
                        SqlCommand consulta = new SqlCommand("select max(Nro_transaccion) from ALL_IN.Pagos");
                        SQLResponse r = db.executeQuery(consulta);
                        int trans = int.Parse(r.result.Rows[0][0].ToString()) + 1;
                            SqlCommand consulta4 = new SqlCommand("insert into ALL_IN.Pagos values ('" + trans.ToString() + "','" + textBox1.Text + "',NULL,'" + couta.ToString() + "')");
                            db.executeQuery(consulta4);
                            int i = 0;
                            
                            for (i = 0; (i <= parent.dataGridView1.Rows.Count - 1); i++)
                            {
                                SqlCommand consulta6 = new SqlCommand("select max(Nro_Pasaje) from ALL_IN.Disponibilidad_Butaca");
                                SQLResponse r6 = db.executeQuery(consulta6);
                                int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                string[] words2 = words[2].Split(' ');
                                string dia1 = words2[0];
                                string mes1 = words[1];
                                string anio1 = words[0];
                                string time1 = words2[1];
                                string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                string[] words3 = parent.dataGridView1.Rows[i].Cells[4].Value.ToString().Split(',');
                                string monto = words3[0];
                                string monto2 = "";
                                int size = words3.Length;
                                if (size == 1)
                                {
                                    monto2 = "0";
                                }
                                else
                                {
                                    monto2 = words3[1];
                                }
                                SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_Butaca values('" + trans6.ToString() + "',Convert(datetime,'" + fecha_salida + "',120),'" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "','" + int.Parse(parent.dataGridView1.Rows[i].Cells[1].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + int.Parse(textBox1.Text) + "','" + trans + "'," + monto + "." + monto2 + ",'0')");
                                db.executeQuery(consulta5);

                            }
                            for (i = 0; (i <= parent.dataGridView3.Rows.Count - 1); i++)
                            {
                                SqlCommand consulta6 = new SqlCommand("select max(Nro_Paquete) from ALL_IN.Disponibilidad_kg");
                                SQLResponse r6 = db.executeQuery(consulta6);
                                int trans6 = int.Parse(r6.result.Rows[0][0].ToString()) + 1;
                                string[] words = parent.dataGridView2.SelectedCells[0].Value.ToString().Split('-');
                                string[] words2 = words[2].Split(' ');
                                string dia1 = words2[0];
                                string mes1 = words[1];
                                string anio1 = words[0];
                                string time1 = words2[1];
                                string fecha_salida = anio1 + "-" + mes1 + "-" + dia1 + " " + time1;
                                
                                DateTime today = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"]);
                                
                                string todaydate = today.ToString("yyyy-MM-dd") + " " + string.Format("{0:HH}", Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["Fecha"])) + ":00:00";
                                
                                string[] words3 = parent.dataGridView3.Rows[i].Cells[1].Value.ToString().Split(',');
                                string monto = words3[0];
                                string monto2 = "";
                                int size = words3.Length;
                                if (size == 1)
                                {
                                    monto2 = "0";
                                }
                                else
                                {
                                    monto2 = words3[1];
                                }
                                string monto5 = monto + "." + monto2;
                                SqlCommand consulta5 = new SqlCommand("insert into ALL_IN.Disponibilidad_kg values('" + trans6.ToString() + "','" + fecha_salida + "','" + parent.dataGridView2.SelectedCells[4].Value.ToString() + "','" + int.Parse(parent.dataGridView2.SelectedCells[3].Value.ToString()) + "',convert(datetime,'" + todaydate + "',120),'" + textBox1.Text + "','" + parent.dataGridView3.Rows[i].Cells[2].Value.ToString() + "','" + trans + "','" + monto5 + "','0')");
                                
                                db.executeQuery(consulta5);
                            }
                            MessageBox.Show("Se ha realizado la compra!." + "\n" + "TOTAL: $" + label2.Text + "\n" + "Nro. Voucher: " + trans); // TODO: Mostrar los datos finales.
                            parent.dataGridView1.Rows.Clear();
                            parent.dataGridView2.Rows.Clear();
                            parent.dataGridView3.Rows.Clear();
                            this.Close();
                    }

                    else//No acepta la compra
                    {
                        //No pasa nada
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            groupBox2.Visible = false;
            button3.Visible = true;
            label3.Visible = true;
            textBox1.Visible = true;
            textBox6.Text = "Efectivo";
            tarjeta = 0;

        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            if (textBox4.Text == "")
            {
                textBox4.Text = "1";
            }
            else if (int.Parse(textBox4.Text) > 12)
            {
                textBox4.Text = "12";
            }
            else if (int.Parse(textBox4.Text) == 0)
            {
                textBox4.Text = "1";
            }
        }
    }
}
